<template>
  <div>
    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="onSelect"
    />
  </div>
</template>

<script>
import Vue from "vue";
import { AddressList } from "vant";
import { getAddressList, updateOrderAddress } from "../../apis/address";

Vue.use(AddressList);
export default {
  name: "AddressList",

  data() {
    return {
      chosenAddressId: 1,
      addressList: [],
      list: [],
    };
  },

  mounted() {},

  methods: {
    onAdd() {
      this.$router.push("/editnewaddress");
    },
    onEdit(item) {
      this.$router.push("/editaddress/" + item.addressid);
      localStorage.setItem("address", JSON.stringify(item));
    },
    async onSelect(item) {
      await updateOrderAddress({
        userid: localStorage.getItem("userid"),
        name: item.name,
        tel: item.tel,
        province: item.province,
        city: item.city,
        county: item.county,
        addressDetail: item.addressDetail,
        time: localStorage.getItem("ordertime"),
      }).then();
      setTimeout(() => {
        this.$router.go(-1);
      }, 1000);
    },
  },

  created() {
    getAddressList({ userid: localStorage.getItem("userid") }).then((data) => {
      this.addressList = data.data.data;
      for (let i = 0; i < this.addressList.length; i++) {
        this.list.push({
          id: i + 1,
          name: this.addressList[i].name,
          tel: this.addressList[i].tel,
          address: this.addressList[i].addressDetail,
          isDefault: this.addressList[i].isDefault,
          addressid: this.addressList[i].addressid,
          province: this.addressList[i].province,
          city: this.addressList[i].city,
          county: this.addressList[i].county,
          addressDetail: this.addressList[i].addressDetail,
        });
         if(this.addressList[i].isDefault){
          this.chosenAddressId=i+1
         }
      }
     
    });
  },
};
</script>

<style  scoped>
</style>